package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/12
 * @description https://algo.cn/problems/remove-duplicates-from-sorted-list/description/
 */
public class Leetcode83_删除排序链表中的重复元素 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 找到重复的节点,将节点的next指向next.next
     * <p>
     * 时间复杂度O(N) 需要遍历一遍链表
     * 空间复杂度O(1)
     */
    public ListNode deleteDuplicates(ListNode head) {
        //边界条件校验
        if (head == null) {
            return head;
        }

        //遍历链表,删除重复元素
        ListNode cur = head;
        while (cur != null) {
            while (cur.next != null && cur.val == cur.next.val) {
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }

        //返回原头节点
        return head;
    }
}
